<?php

namespace app\admin\controller\kuerp\noticemanage;


use app\admin\model\kuerp\Commonseal;
use app\common\controller\Backend;
use addons\kuerp\model\Message as MessageModel;
use addons\kuerp\model\Notice as NoticeModel;
use addons\kuerp\model\NoticeRead;
use addons\kuerp\model\Record as RecordModel;
use app\admin\model\kuerp\GoodsSales;
use app\admin\model\kuerp\Expense;
use app\admin\model\ScoreApply;
use addons\kuerp\model\Staff;
use think\Db;
use think\Exception;
use addons\kuerp\model\ExamineRecord;
use app\admin\model\department\Admin;
use app\admin\model\kuerp\StaffMember;

use addons\kuerp\model\Record;

class Message extends Backend
{
    protected $relationSearch = true;
    protected $noNeedRight = ['get_message_number', 'news', 'newsReadAll'];

    protected $model = null;
    protected $type = [];


    public function _initialize()
    {
        parent::_initialize();
        $this->type = array(
            array(
                'id'=>1,
                'pid'=>0,
                'name'=>'消息提醒',
                'text'=>'消息提醒',
            ),
            array(
                'id'=>1,
                'pid'=>0,
                'name'=>'公告',
                'text'=>'消息提醒',
            ),
            array(
                'id'=>1,
                'pid'=>0,
                'name'=>'今日需联系客户',
                'text'=>'消息提醒',
            ),
        );

        $this->assignconfig('typeList', $this->type);
    }
    /**
     * 待办列表
     */
    public function index(){

        //消息提醒
        $whereNew = [
            'status'=>0,
            'to_staff_id' => $this->auth->id ,
            'relation_type'=>['not in','examine,discuss,sign']
        ];
        $news = MessageModel::where($whereNew)->count();
        //公告
        $noticeid = NoticeModel::where([])->column('id');
        foreach($noticeid as $k=>$v){
            $read = NoticeRead::where(['notice_id'=>$v,'admin_id'=>$this->auth->id])->find();
            if($read){
                unset($noticeid[$k]);
                continue;
            }
        }
        $notice = count($noticeid);
        $start = date('Y-m-d 00:00:00');
        $end = date('Y-m-d 23:59:59');
        $where['createtime'] = array(array('egt',strtotime($start)),array('elt',strtotime($end)));
        $whereR['next_time'] = array(array('egt',$start),array('elt',$end));
        //待线索跟进
        $whereLead['create_staff_id'] = $this->auth->id;
        $whereLead['relation_type'] = 4;
        $whereLead['status'] = 0;
        $lead   = 0;//Record::where($whereLead)->where($whereR)->count();

        $whereCustomer['admin_id'] = $this->auth->id;
        $whereCustomer['relation_type'] = 1;
        $whereCustomer['status'] = 0;
        $customer   = Record::where($whereCustomer)->where($whereR)->count();

        $whereBusiness['create_staff_id'] = $this->auth->id;
        $whereBusiness['relation_type'] = 5;
        $whereBusiness['status'] = 0;
        $business   = 0;//Record::where($whereBusiness)->where($whereR)->count();

        $whereContract['create_staff_id'] = $this->auth->id;
        $whereContract['relation_type'] = 3;
        $whereContract['status'] = 0;
        $contract   = 0;//Record::where($whereContract)->where($whereR)->count();
        //系统设置特定审核人员
        $config_examine_admins = config('site.examine_admins');
        $adminids = $this->auth->adminids;
        $childrenSales = $this->auth->childrenSales;
        if (!empty($config_examine_admins[$this->auth->id])) {
            $adminids = array_merge($adminids,explode(',', $config_examine_admins[$this->auth->id]));
            //获取对应销售id
            $config_sale_users = (new StaffMember())->getStaffMemberIds($adminids);
            $childrenSales = array_merge($childrenSales,$config_sale_users);
        }
        //报销单审批
        $expense = 0;
        if ($this->auth->check('examine/expense/examine')) {
            $wheres = [
                // 'createtime' => $where['createtime'],
                'admin_id' => ['in', $adminids],
                'check_status' => 1,
                'check_uids' => ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',check_uids) = 0')],
            ];
            //获取审批流程
            $flows = Db::name('flows')->where('relation_type', 'expense')->where('status', 1)->find();
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                $examine_index = 0;
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        // break;
                    }
                }
                if ($examine_index > 0) {
                    $wheres['check_step_sort'] = $examine_index - 1;
                    $expense = Expense::where($wheres)->count();
                }
            }
        }
        //费用审核
        $consume = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::CONSUME_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        //获取直属下级
        $children_ids = [];
        $department_ids = Admin::getPrincipalIds($this->auth->id);
        if ($department_ids) {
            $children_ids = Admin::getDepartmentAdminIds($department_ids, true);
            $children_ids = !empty($config_examine_admins[$this->auth->id]) ? array_merge($children_ids, explode(',', $config_examine_admins[$this->auth->id])) : $children_ids;
        }
        //待审核合同
        $examine = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::CONTRACT_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        if ($this->auth->check('examine/goods_sales/examine')) {
            $wheres = [
                // 'purchase_time' => $where['createtime'],
                'sale_user' => ['in', $childrenSales],
                'examine_status' => 0,
                'examine_adminids' => ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',examine_adminids) = 0')],
            ];
            //获取审批流程
            $flows = Db::name('flows')->where('relation_type', 'goods_sale')->where('status', 1)->find();
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                $examine_index = 0;
                $last_examine_indexs = [];
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        $last_examine_indexs[] = $key;
                        // break;
                    }
                }
                if ($examine_index > 0) {
                    //当前用户存在多级审核且存在第一级审核时 需要获取该用户的直属下级
                    $first_children_ids = [];
                    $search_index = array_search(0, $last_examine_indexs);
                    if(count($last_examine_indexs) > 1 && $search_index !== false) {
                        //获取直属下级
                        // $department_ids = Admin::getPrincipalIds($this->auth->id);
                        // if ($department_ids) {
                            // $children_ids = Admin::getDepartmentAdminIds($department_ids, true);
                            // $children_ids = !empty($config_examine_admins[$this->auth->id]) ? array_merge($children_ids, explode(',', $config_examine_admins[$this->auth->id])) : $children_ids;
                            if ($children_ids) {
                                $first_children_ids = (new StaffMember())->getStaffMemberIds($children_ids);
                            }
                        // }
                        $last_examine_indexs = array_values(array_diff($last_examine_indexs, [0]));
                    }
                    if (!empty($first_children_ids)) {
                        if ($last_examine_indexs) {
                            $wheres['id'] = ['exp', Db::raw('> 0 and ( (examine_index = 0 and sale_user in ('.implode(',', $first_children_ids).'))  OR (examine_index '.(count($last_examine_indexs) == 1 ? '='.$last_examine_indexs[0] : ' in ('.implode(',', $last_examine_indexs).')').' and sale_user in ('.implode(',', $childrenSales).')))')];
                        } else {
                            $wheres['examine_index'] = 0;
                        }
                    } else {
                        $wheres['examine_index'] = count($last_examine_indexs) == 1 ? $last_examine_indexs[0] : ['in', $last_examine_indexs];
                    }
                    // $wheres['examine_index'] = ['<', $examine_index ? : 1];
                    // if ($examine_index == count($flows['flow_items'])) {
                    //     $wheres['examine_index'] = ['>', 0];
                    // }
                    $examine = GoodsSales::where($wheres)->count();
                }
            }
        }
        //待审核积分申请单
        $score = 0;
        if ($this->auth->check('score_apply/examine')) {
            $wheres = [
                'admin_id' => ['in', $adminids],
                'check_status' => 1,
                'check_uids' => ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',check_uids) = 0')],
            ];
            //获取审批流程
            $flows = Db::name('flows')->where('relation_type', 'score')->where('status', 1)->find();
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                $examine_index = 0;
                $last_examine_indexs = [];
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        $last_examine_indexs[] = $key;
                        // break;
                    }
                }
                
                if ($examine_index > 0) {
                    $first_children_ids = [];
                    //当前用户存在多级审核且存在第一级审核时 需要获取该用户的直属下级
                    $search_index = array_search(0, $last_examine_indexs);
                    if(count($last_examine_indexs) > 1 && $search_index !== false) {
                        $first_children_ids = $children_ids?$children_ids:[];
                        $last_examine_indexs = array_values(array_diff($last_examine_indexs, [0]));
                    }
                    if (!empty($first_children_ids)) {
                        if ($last_examine_indexs) {
                            $wheres['id'] = ['exp', Db::raw('> 0 and ( (check_step_sort = 0 and admin_id in ('.implode(',', $first_children_ids).'))  OR (check_step_sort '.(count($last_examine_indexs) == 1 ? '='.$last_examine_indexs[0] : ' in ('.implode(',', $last_examine_indexs).')').' and admin_id in ('.implode(',', $adminids).')))')];
                        } else {
                            $wheres['check_step_sort'] = 0;
                        }
                    } else {
                        $wheres['check_step_sort'] = count($last_examine_indexs) == 1 ? $last_examine_indexs[0] : ['in', $last_examine_indexs];
                    }
                    // $wheres['check_step_sort'] = $examine_index - 1;
                    $score = ScoreApply::where($wheres)->count();
                }
            }
        }

        $commonseal = 0;
        if ($this->auth->check('kuerp/commonseal/examine')) {
            $wheres = [
                'admin_id' => ['in', $adminids],
                'check_status' => 1,
                'check_uids' => ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',check_uids) = 0')],
            ];
            //获取审批流程
            $flows = Db::name('flows')->where('relation_type', 'common_seal')->where('status', 1)->find();
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                $examine_index = 0;
                $last_examine_indexs = [];
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        $last_examine_indexs[] = $key;
                        // break;
                    }
                }

                if ($examine_index > 0) {
                    $first_children_ids = [];
                    //当前用户存在多级审核且存在第一级审核时 需要获取该用户的直属下级
                    $search_index = array_search(0, $last_examine_indexs);
                    if(count($last_examine_indexs) > 1 && $search_index !== false) {
                        $first_children_ids = $children_ids?$children_ids:[];
                        $last_examine_indexs = array_values(array_diff($last_examine_indexs, [0]));
                    }
                    if (!empty($first_children_ids)) {
                        if ($last_examine_indexs) {
                            $wheres['id'] = ['exp', Db::raw('> 0 and ( (check_step_sort = 0 and admin_id in ('.implode(',', $first_children_ids).'))  OR (check_step_sort '.(count($last_examine_indexs) == 1 ? '='.$last_examine_indexs[0] : ' in ('.implode(',', $last_examine_indexs).')').' and admin_id in ('.implode(',', $adminids).')))')];
                        } else {
                            $wheres['check_step_sort'] = 0;
                        }
                    } else {
                        $wheres['check_step_sort'] = count($last_examine_indexs) == 1 ? $last_examine_indexs[0] : ['in', $last_examine_indexs];
                    }
                    // $wheres['check_step_sort'] = $examine_index - 1;
                    $commonseal = Commonseal::where($wheres)->count();
                }
            }
        }
        //待审核回款
        $receivables = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::RECEIVABLES_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id,
        // ])->count();
        //待审批办公
        $approval = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::APPROVAL_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id,
        // ])->count();

        //业绩审核
        $achievement = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::ACHIEVEMENT_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();

        //待入库审批
        $partin = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::PARTS_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        //待报价审批
        $quote = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::QUOTE_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        //待处理工单
        // $whereStaff = function ($query) {
        //     $query->where('create_staff_id|owner_staff_id', 'in', Staff::getMyStaffIds())
        //         ->whereOr('', 'exp', "FIND_IN_SET({$this->auth->id},show_staff_id)");
        // };

        //待发票审批
        $invoice = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::INVOICE_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        //待发货审批
        $delivery = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::DELIVERY_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        // //待入库审批
        $instock = 0;// ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::INSTOCK_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        // //待出库审批
        $outstock = 0;// ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::OUTSTOCK_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        $info = array(
            'customer'=>$customer,
            'contract'=>$contract,
            'lead'=>$lead,
            'consume'=>$consume,
            'news'=>$news,
            'examine'=>$examine,
            'receivables'=>$receivables,
            'approval'=>$approval,
            'notice'=>$notice,
            'achievement'=>$achievement,
            'business'=>$business,
            'partin'=>$partin,
            'quote'=>$quote,
            'invoice'=>$invoice,
            'delivery'=>$delivery,
            'instock'=>$instock,
            'outstock'=>$outstock,
            'expense'=>$expense,
            'score'=>$score,
            'commonseal'=>$commonseal,
        );
        $this->view->assign('row',$info);
        $this->assignconfig("info", ['time' => date('Y-m-d 00:00:00').' - '.date('Y-m-d 23:59:59')]);
        //获取报销人列表 搜索
        // $adminids = $this->auth->adminids;
        $adminlist = Db::name("admin")->where("id", 'in', $adminids)->column("nickname","id");
        $this->assignconfig("adminlist", $adminlist);
        $stafflist = Db::name("kuerp_staff_member")->where("admin_id", 'in', $adminids)->column("name","id");
        $this->assignconfig("stafflist", $stafflist);
        $this->assignconfig("commonSealList", (new Commonseal())->getCommonSealList());
        $this->assignconfig("usedeatilList",(new Commonseal())->getUsedeatilList());
        return $this->view->fetch();
    }
    /**
     * 获取通知数量
     */
    public function get_message_number(){
        //消息提醒
        $whereNew = ['status'=>0,'to_staff_id' => $this->auth->id ,'relation_type'=>['not in','examine']];
        $news = MessageModel::where($whereNew)->count();
        //公告
        $noticeid = NoticeModel::where([])->column('id');
        foreach($noticeid as $k=>$v){
            $read = NoticeRead::where(['notice_id'=>$v,'admin_id'=>$this->auth->id])->find();
            if($read){
                unset($noticeid[$k]);
                continue;
            }
        }
        $notice = count($noticeid);
        $start = date('Y-m-d 00:00:00');
        $end = date('Y-m-d 23:59:59');
        $where['createtime'] = array(array('egt',strtotime($start)),array('elt',strtotime($end)));
        $whereR['next_time'] = array(array('egt',$start),array('elt',$end));
        //待线索跟进
        $whereLead['admin_id'] = $this->auth->id;
        $whereLead['relation_type'] = 4;
        $whereLead['status'] = 0;
        $lead   = 0;//Record::where($whereLead)->where($whereR)->count();

        $whereCustomer['admin_id'] = $this->auth->id;
        $whereCustomer['relation_type'] = 1;
        $whereCustomer['status'] = 0;
        $customer   = Record::where($whereCustomer)->where($whereR)->count();

        $whereBusiness['admin_id'] = $this->auth->id;
        $whereBusiness['relation_type'] = 5;
        $whereBusiness['status'] = 0;
        $business   = 0;//Record::where($whereBusiness)->where($whereR)->count();

        $whereContract['create_staff_id'] = $this->auth->id;
        $whereContract['relation_type'] = 3;
        $whereContract['status'] = 0;
        $contract   = 0;//Record::where($whereContract)->where($whereR)->count();
        //系统设置特定审核人员
        $config_examine_admins = config('site.examine_admins');
        $adminids = $this->auth->adminids;
        $childrenSales = $this->auth->childrenSales;
        if (!empty($config_examine_admins[$this->auth->id])) {
            $adminids = array_merge($adminids,explode(',', $config_examine_admins[$this->auth->id]));
            //获取对应销售id
            $config_sale_users = (new StaffMember())->getStaffMemberIds($adminids);
            $childrenSales = array_merge($childrenSales,$config_sale_users);
        }
        //报销单审批
        $expense = 0;
        if ($this->auth->check('examine/expense/examine')) {
            $wheres = [
                // 'createtime' => $where['createtime'],
                'admin_id' => ['in', $adminids],
                'check_status' => 1,
                'check_uids' => ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',check_uids) = 0')],
            ];
            //获取审批流程
            $flows = Db::name('flows')->where('relation_type', 'expense')->where('status', 1)->find();
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                $examine_index = 0;
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        // break;
                    }
                }
                if ($examine_index > 0) {
                    $wheres['check_step_sort'] = $examine_index - 1;
                    $expense = Expense::where($wheres)->count();
                }
            }
        }

        //费用审核
        $consume = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::CONSUME_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        //获取直属下级
        $children_ids = [];
        $department_ids = Admin::getPrincipalIds($this->auth->id);
        if ($department_ids) {
            $children_ids = Admin::getDepartmentAdminIds($department_ids, true);
            $children_ids = !empty($config_examine_admins[$this->auth->id]) ? array_merge($children_ids, explode(',', $config_examine_admins[$this->auth->id])) : $children_ids;
        }
        //待审核合同
        $examine = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::CONTRACT_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        if ($this->auth->check('examine/goods_sales/examine')) {
            $wheres = [
                // 'purchase_time' => $where['createtime'],
                'sale_user' => ['in', $childrenSales],
                'examine_status' => 0,
                'examine_adminids' => ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',examine_adminids) = 0')],
            ];
            //获取审批流程
            $flows = Db::name('flows')->where('relation_type', 'goods_sale')->where('status', 1)->find();
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                $examine_index = 0;
                $last_examine_indexs = [];
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        $last_examine_indexs[] = $key;
                        // break;
                    }
                }
                if ($examine_index > 0) {
                    //当前用户存在多级审核且存在第一级审核时 需要获取该用户的直属下级
                    $first_children_ids = [];
                    $search_index = array_search(0, $last_examine_indexs);
                    if(count($last_examine_indexs) > 1 && $search_index !== false) {
                        //获取直属下级
                        // $department_ids = Admin::getPrincipalIds($this->auth->id);
                        // if ($department_ids) {
                            // $children_ids = Admin::getDepartmentAdminIds($department_ids, true);
                            // $children_ids = !empty($config_examine_admins[$this->auth->id]) ? array_merge($children_ids, explode(',', $config_examine_admins[$this->auth->id])) : $children_ids;
                            if ($children_ids) {
                                $first_children_ids = (new StaffMember())->getStaffMemberIds($children_ids);
                            }
                        // }
                        $last_examine_indexs = array_values(array_diff($last_examine_indexs, [0]));
                    }
                    if (!empty($first_children_ids)) {
                        if ($last_examine_indexs) {
                            $wheres['id'] = ['exp', Db::raw('> 0 and ( (examine_index = 0 and sale_user in ('.implode(',', $first_children_ids).'))  OR (examine_index '.(count($last_examine_indexs) == 1 ? '='.$last_examine_indexs[0] : ' in ('.implode(',', $last_examine_indexs).')').' and sale_user in ('.implode(',', $childrenSales).')))')];
                        } else {
                            $wheres['examine_index'] = 0;
                        }
                    } else {
                        $wheres['examine_index'] = count($last_examine_indexs) == 1 ? $last_examine_indexs[0] : ['in', $last_examine_indexs];
                    }
                    // $wheres['examine_index'] = ['<', $examine_index ? : 1];
                    // if ($examine_index == count($flows['flow_items'])) {
                    //     $wheres['examine_index'] = ['>', 0];
                    // }
                    $examine = GoodsSales::where($wheres)->count();
                }
            }
        }
        //待审核积分申请单
        $score = 0;
        if ($this->auth->check('score_apply/examine')) {
            $wheres = [
                'admin_id' => ['in', $adminids],
                'check_status' => 1,
                'check_uids' => ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',check_uids) = 0')],
            ];
            //获取审批流程
            $flows = Db::name('flows')->where('relation_type', 'score')->where('status', 1)->find();
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                $examine_index = 0;
                $last_examine_indexs = [];
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        $last_examine_indexs[] = $key;
                        // break;
                    }
                }
                
                if ($examine_index > 0) {
                    $first_children_ids = [];
                    //当前用户存在多级审核且存在第一级审核时 需要获取该用户的直属下级
                    $search_index = array_search(0, $last_examine_indexs);
                    if(count($last_examine_indexs) > 1 && $search_index !== false) {
                        $first_children_ids = $children_ids?$children_ids:[];
                        $last_examine_indexs = array_values(array_diff($last_examine_indexs, [0]));
                    }
                    if (!empty($first_children_ids)) {
                        if ($last_examine_indexs) {
                            $wheres['id'] = ['exp', Db::raw('> 0 and ( (check_step_sort = 0 and admin_id in ('.implode(',', $first_children_ids).'))  OR (check_step_sort '.(count($last_examine_indexs) == 1 ? '='.$last_examine_indexs[0] : ' in ('.implode(',', $last_examine_indexs).')').' and admin_id in ('.implode(',', $adminids).')))')];
                        } else {
                            $wheres['check_step_sort'] = 0;
                        }
                    } else {
                        $wheres['check_step_sort'] = count($last_examine_indexs) == 1 ? $last_examine_indexs[0] : ['in', $last_examine_indexs];
                    }
                    // $wheres['check_step_sort'] = $examine_index - 1;
                    $score = ScoreApply::where($wheres)->count();
                }
            }
        }

        //待审核公章申请单
        $commonseal = 0;
        if ($this->auth->check('kuerp/commonseal/examine')) {
            $wheres = [
                'admin_id' => ['in', $adminids],
                'check_status' => 1,
                'check_uids' => ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',check_uids) = 0')],
            ];
            //获取审批流程
            $flows = Db::name('flows')->where('relation_type', 'common_seal')->where('status', 1)->find();
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                $examine_index = 0;
                $last_examine_indexs = [];
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        $last_examine_indexs[] = $key;
                        // break;
                    }
                }

                if ($examine_index > 0) {
                    $first_children_ids = [];
                    //当前用户存在多级审核且存在第一级审核时 需要获取该用户的直属下级
                    $search_index = array_search(0, $last_examine_indexs);
                    if(count($last_examine_indexs) > 1 && $search_index !== false) {
                        $first_children_ids = $children_ids?$children_ids:[];
                        $last_examine_indexs = array_values(array_diff($last_examine_indexs, [0]));
                    }
                    if (!empty($first_children_ids)) {
                        if ($last_examine_indexs) {
                            $wheres['id'] = ['exp', Db::raw('> 0 and ( (check_step_sort = 0 and admin_id in ('.implode(',', $first_children_ids).'))  OR (check_step_sort '.(count($last_examine_indexs) == 1 ? '='.$last_examine_indexs[0] : ' in ('.implode(',', $last_examine_indexs).')').' and admin_id in ('.implode(',', $adminids).')))')];
                        } else {
                            $wheres['check_step_sort'] = 0;
                        }
                    } else {
                        $wheres['check_step_sort'] = count($last_examine_indexs) == 1 ? $last_examine_indexs[0] : ['in', $last_examine_indexs];
                    }
                    // $wheres['check_step_sort'] = $examine_index - 1;
                    $commonseal = Commonseal::where($wheres)->count();
                }
            }
        }
        //待审核回款
        $receivables = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::RECEIVABLES_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id,
        // ])->count();
        //待审批办公
        $approval = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::APPROVAL_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id,
        // ])->count();

        //业绩审核
        $achievement = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::ACHIEVEMENT_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();

        //待入库审批
        $partin = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::PARTS_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        //待报价审批
        $quote = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::QUOTE_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();

        //待发票审批
        $invoice = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::INVOICE_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        //待发货审批
        $delivery = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::DELIVERY_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        //待入库审批
        $instock = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::INSTOCK_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        //待出库审批
        $outstock = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::OUTSTOCK_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        $info = array(
            'customer'=>$customer,
            'contract'=>$contract,
            'lead'=>$lead,
            'consume'=>$consume,
            'news'=>$news,
            'examine'=>$examine,
            'receivables'=>$receivables,
            'approval'=>$approval,
            'notice'=>$notice,
            'achievement'=>$achievement,
            'business'=>$business,
            'partin'=>$partin,
            'quote'=>$quote,
            'invoice'=>$invoice,
            'delivery'=>$delivery,
            'instock'=>$instock,
            'outstock'=>$outstock,
            'expense'=>$expense,
            'score'=>$score,
            'commonseal'=>$commonseal,
        );
        $number=array_sum(array_values($info));
        $info['number']=$number;
        $this->success('请求成功','',$info);
    }

    /**
     * 提醒消息
     */
    public function news()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $wheres = ['to_staff_id' => $this->auth->id,'relation_type'=>['not in','examine']];
            $list = MessageModel::where($where)->where($wheres)->with(['fromStaff', 'examine'])->order('status asc,id desc')->paginate($limit);

            foreach($list as $k=>$v){

                $list[$k]['relation_name'] = MessageModel::messageType($v['relation_type'],$v['relation_id']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 公告
     */
    public function notice()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $wheres = [];
            $filter = json_decode($this->request->get("filter", ''), true);
            $op = json_decode($this->request->get("op", '','trim'), true);
            if (isset($filter['is_read'])) {
                // 自定义处理
                $is_read = $filter['is_read'];
                // 处理完可以去掉也可以覆盖重构
                unset($filter['is_read'],$op['is_read']);
                $read_ids = NoticeRead::where(['admin_id'=>$this->auth->id])->column('notice_id');
                if ($is_read) {
                    $wheres['id'] = ['IN', $read_ids];
                } else {
                    $wheres['id'] = ['NOT IN', $read_ids];
                }
            }
            $this->request->get(['filter'=>json_encode($filter,true)]);
            $this->request->get(['op'=>json_encode($op,true)]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = NoticeModel::where($where)->where($wheres)->order('id desc')->paginate($limit);
            foreach ($list as $k => $v) {
                $read = NoticeRead::where(['notice_id'=>$v['id'],'admin_id'=>$this->auth->id])->find();
                $read_admin_ids = explode(',', $v['read_admin_ids']);
                $list[$k]['is_read']   = in_array($this->auth->id, $read_admin_ids)?1:0;
                $list[$k]['content'] = strip_tags(htmlspecialchars_decode($v['content']));
            }
            $arr = $list->items();
            array_multisort($arr,SORT_DESC);
            $result = array("total" => $list->total(), "rows" => $arr);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 待线索跟进记录列表
     */
    public function leads() {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $staff = Staff::info();
            //0:全部 1：我负责的 2：下属负责的
            $type = input('type',1);
            switch($type){
                case 1:
                    $wheres['create_staff_id'] =  $staff->id;
                    break;
                case 2:
                    $wheres['create_staff_id'] =  array('in',Staff::getLowerStaffId());
                    break;
                default:
                    $wheres['create_staff_id'] =  array('in',Staff::getMyStaffIds());
                    break;

            }
            $wheres['relation_type'] = 4;
            $wheres['status'] = 0;
            $list   = Record::where($where)->where($wheres)->with(['staff','leads'])->order($sort, $order)->paginate($limit);
            $row    = $list->items();
            $result = array("total" => $list->total(), "rows" => $row);

            return json($result);
        }

        return $this->view->fetch();
    }
    /**
     * 待客户跟进记录列表
     */
    public function customer() {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $staff = Staff::info();
            //0:全部 1：我负责的 2：下属负责的
            $type = input('type',1);
            switch($type){
                case 1:
                    $wheres['create_staff_id'] =  $this->auth->staff_member_id ?? $staff->id;
                    break;
                case 2:
                    $childrenSales = $this->auth->childrenSales;
                    //本人存在 则剔除自己
                    if (in_array($this->auth->staff_member_id,$childrenSales)) {
                        $childrenSales = array_diff($childrenSales, [$this->auth->staff_member_id]);
                    }
                    $where['create_staff_id'] = ['in', $childrenSales];
                    break;
                default:
                    $wheres['create_staff_id'] =  ['in', $this->auth->childrenSales];
                    break;

            }
            $wheres['relation_type'] = 1;
            $wheres['status'] = 0;
            $list   = Record::where($where)->where($wheres)->with(['staff','customer'])->order($sort, $order)->paginate($limit);
            $row    = $list->items();
            $result = array("total" => $list->total(), "rows" => $row);

            return json($result);
        }

        return $this->view->fetch();
    }
    /**
     * 待商机跟进记录列表
     */
    public function business() {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $staff = Staff::info();
            //0:全部 1：我负责的 2：下属负责的
            $type = input('type',1);
            switch($type){
                case 1:
                    $wheres['create_staff_id'] =  $staff->id;
                    break;
                case 2:
                    $wheres['create_staff_id'] =  array('in',Staff::getLowerStaffId());
                    break;
                default:
                    $wheres['create_staff_id'] =  array('in',Staff::getMyStaffIds());
                    break;

            }
            $wheres['relation_type'] = 5;
            $wheres['status'] = 0;
            $list   = Record::where($where)->where($wheres)->with(['staff','business'])->order($sort, $order)->paginate($limit);
            $row    = $list->items();
            $result = array("total" => $list->total(), "rows" => $row);

            return json($result);
        }

        return $this->view->fetch();
    }
    /**
     * 待合同跟进记录列表
     */
    public function contract() {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //0:全部 1：我负责的 2：下属负责的
            $type = input('type',1);
            switch($type){
                case 1:
                    $wheres['create_staff_id'] =  $this->auth->id;
                    break;
                case 2:
                    $wheres['create_staff_id'] =  array('in',Staff::getLowerStaffId());
                    break;
                default:
                    $wheres['create_staff_id'] =  array('in',Staff::getMyStaffIds());
                    break;

            }
            $wheres['relation_type'] = 3;
            $wheres['status'] = 0;
            $list   = Record::where($where)->where($wheres)->with(['staff','contract'])->order($sort, $order)->paginate($limit);
            $row    = $list->items();
            $result = array("total" => $list->total(), "rows" => $row);

            return json($result);
        }

        return $this->view->fetch();
    }

    public function newsReadAll(){
        $whereNew = ['status'=>0,'to_staff_id' => $this->auth->id ,'relation_type'=>['not in','examine']];
        $res = MessageModel::where($whereNew)->update(['read_time' => time(), 'status' => 1]);
        if ($res !== false) {
            return $this->success('操作成功');
        } else {
            return $this->error('操作失败');
        }
    }

}